<?php
include_once('mapping.php');
include_once('ach_pds.php');
include_once('constants.php');

class utilities{
    public static function getFCN(){
        $fcn = '';
        $nextFcn = '';

        $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('could not connect');
        try {
            mysql_select_db(DB_NAME);
            $sel = 'select * from config where group_id=1 and key_name='.'\''.'fcn'.'\'';
	        $res = mysql_query($sel);
            $row = mysql_fetch_assoc($res);
            $fcn = $row['value'];

            if ($fcn == 9999){
                $nextFcn = 1;
                $_count = 4 - strlen($nextFcn);

                // fill leading 0
                for ($i=0; $i<$_count; $i++){
                    $nextFcn = '0'.$nextFcn;
                }
            }
            else if ($fcn < 9999){
                $nextFcn = $fcn + 1;
                $_count = 4 - strlen($nextFcn);

                // fill leading 0
                for ($i=0; $i<$_count; $i++){
                    $nextFcn = '0'.$nextFcn;
                }
            }
            else {
                die('unknown error in getFCN');
            }

            $upd = 'update config set value='.'\''.$nextFcn.'\''.' where group_id=1 and key_name='.'\''.'fcn'.'\'';
            // update fcn value
            mysql_query($upd);
        }
        catch (Exception $e){
            echo 'getFCN has error '.$e->getMessage;
            mysql_close($con);
        }

		if (MODE == 'TEST'){
			$fcn = 'TEST';
		}
		
        return $fcn;
    }

    public static function getJD(){
        $jul = '';
        $jul = date('m/d/Y');
		$jul = utilities::getJDFrom($jul);
        return $jul;
    }

    public static function getPN(){
        $fcn = '';
        $nextFcn = '';

        $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('could not connect');
        try {
            mysql_select_db(DB_NAME);
            $sel = 'select * from config where group_id=1 and key_name='.'\''.'pn'.'\'';
	        $res = mysql_query($sel);
            $row = mysql_fetch_assoc($res);
            $fcn = $row['value'];

            if ($fcn == 99){
                $nextFcn = 1;
                $_count = 2 - strlen($nextFcn);

                // fill leading 0
                for ($i=0; $i<$_count; $i++){
                    $nextFcn = '0'.$nextFcn;
                }
            }
            else if ($fcn < 9999){
                $nextFcn = $fcn + 1;
                $_count = 2 - strlen($nextFcn);

                // fill leading 0
                for ($i=0; $i<$_count; $i++){
                    $nextFcn = '0'.$nextFcn;
                }
            }
            else {
                die('unknown error in getPN');
            }

            $upd = 'update config set value='.'\''.$nextFcn.'\''.' where group_id=1 and key_name='.'\''.'pn'.'\'';
            // update pn value
            mysql_query($upd);
        }
        catch (Exception $e){
            echo 'getPN has error '.$e->getMessage;
            mysql_close($con);
        }

        return $fcn;
    }

    // string format must be mm/dd/YYYY
    public static function getJDFrom($str){
        $parts = split('\/',$str);
        $timeStamp = mktime(0, 0, 0, $parts[0], $parts[1]+1, $parts[2]);
        $yearPart = date('Y',$timeStamp);
		$dayPart = date('z',$timeStamp);
		
		if (strlen($dayPart) < 3){
			$dayPart = '0'.$dayPart;
		}
		
		return $yearPart.$dayPart;
    }

    // it generates file for collecting
    // todo, what's the id to be updated after approved
    public static function db2PAD($res){
        global $DB2RECORD_PAD;

        $fieldsConPat = '/\.\./';
        $fieldsAddPat = '/\+/';

        try {
            // perparing pad object
            $recCount = 1;
            $recNum = mysql_num_rows($res);
            $totalD = 0;
            $pad = new ach_dom_pad;
            $pad->init();
            $header = $pad->getHeader();
            $trailor = $pad->getTrailor();
            
            $headerFields = $header->getFields();
            $headerFields[0]->setValue(utilities::getFilledNum($recCount,6));

            $trailorFields = $trailor->getFields();
            $trailorFields[0]->setValue(utilities::getFilledNum($recCount+$recNum+1,6));
            $trailorFields[6]->setValue($recNum);

            while ($row = mysql_fetch_assoc($res)){
                $totalD += $row['MONEYAMOUNT'];
                $record = $pad->init_record();
		        $recFields = $record->getFields();

                $recFields[0]->setValue(utilities::getFilledNum($recCount+1,6));
		        $keys = array_keys($DB2RECORD_PAD);
                $matches = array();
		        foreach ($keys as $key){
                    $value = $DB2RECORD_PAD[$key];
                    if (preg_match_all($fieldsConPat, $key, $matches) > 0){
                        $keyParts = split('\.\.',$key);
                        $realKey = '';
                        foreach ($keyParts as $var){
                            if ($realKey == ''){
                                $realKey .= $row[$var];
                            }
                            else {
                                $realKey .= ' '.$row[$var];
                            }
                        }
                        utilities::setValueFromExp($value, $recFields, $realKey);
                    }
                    else if (preg_match_all($fieldsAddPat, $key, $matches) > 0){
                        $keyParts = split('\+',$key);
                        $realKey = 0;
                        foreach ($keyParts as $var){
                            $realKey += $row[$var];
                        }
                        utilities::setValueFromExp($value, $recFields, $realKey);
                    }
                    else {
                        utilities::setValueFromExp($value, $recFields, $row[$key]);
                    }
		        }

                $recCount++;
                $pad->addRecord($record);
            }

            $trailorFields[7]->setValue(utilities::getMoney($totalD));

            //$upd = 'update applications set value='.'\''.$nextFcn.'\''.' where group_id=1 and key_name='.'\''.'fcn'.'\'';
            // update generated record to other status to avoid duplication
            //mysql_query($upd);
        }
        catch (Exception $e){
            echo 'db2PAD has error '.$e->getMessage;
        }

        return $pad;
    }

    // it generates file for deposit
    // todo, what's the id to be updated after approved
    public static function db2PDS($res){
        global $DB2RECORD_PDS;

        $fieldsConPat = '/\.\./';
        $fieldsAddPat = '/\+/';

        try {
            // perparing pad object
            $recCount = 1;
            $recNum = mysql_num_rows($res);
            $totalD = 0;
            $pds = new ach_dom_pds;
            $pds->init();
            $header = $pds->getHeader();
            $trailor = $pds->getTrailor();
            
            $headerFields = $header->getFields();
            $headerFields[0]->setValue(utilities::getFilledNum($recCount,6));

            $trailorFields = $trailor->getFields();
            $trailorFields[0]->setValue(utilities::getFilledNum($recCount+$recNum+1,6));
            $trailorFields[4]->setValue($recNum);

            while ($row = mysql_fetch_assoc($res)){
                $totalD += $row['ApprovalAmount'];
                $record = $pds->init_record();
		        $recFields = $record->getFields();

                $recFields[0]->setValue(utilities::getFilledNum($recCount+1,6));
		        $keys = array_keys($DB2RECORD_PDS);
                $matches = array();
		        foreach ($keys as $key){
                    $value = $DB2RECORD_PDS[$key];
                    if (preg_match_all($fieldsConPat, $key, $matches) > 0){
                        $keyParts = split('\.\.',$key);
                        $realKey = '';
                        foreach ($keyParts as $var){
                            if ($realKey == ''){
                                $realKey .= $row[$var];
                            }
                            else {
                                $realKey .= ' '.$row[$var];
                            }
                        }
                        utilities::setValueFromExp($value, $recFields, $realKey);
                    }
                    else if (preg_match_all($fieldsAddPat, $key, $matches) > 0){
                        $keyParts = split('\+',$key);
                        $realKey = 0;
                        foreach ($keyParts as $var){
                            $realKey += $row[$var];
                        }
                        utilities::setValueFromExp($value, $recFields, $realKey);
                    }
                    else {
                        utilities::setValueFromExp($value, $recFields, $row[$key]);
                    }
		        }

                $recCount++;
                $pds->addRecord($record);
            }

            $trailorFields[5]->setValue(utilities::getMoney($totalD));

            //$upd = 'update applications set value='.'\''.$nextFcn.'\''.' where group_id=1 and key_name='.'\''.'fcn'.'\'';
            // update generated record to other status to avoid duplication
            //mysql_query($upd);
        }
        catch (Exception $e){
            echo 'db2PDS has error '.$e->getMessage;
        }

        return $pds;
    }

    public static function setValueFromExp($str, $fields, $key){
        $expValuePat = '/\,/';
        $matches = array();
        $value = '';
        
        if (preg_match_all($expValuePat, $str, $matches) > 0){
            $parts = split(',',$str);
            $pos = $parts[0];
            $type = $parts[1];
            $valueStr = $parts[2];
            
            $valueParts = split('-',$valueStr);
            if ($valueParts[0] == 'FC'){
                $comm = $valueParts[1];
                $val = '';
                if ($type == 'string' || $type == 'money'){
                    $val = eval('return '.$comm.'(\''.$key.'\');');
                }
                else {
                    $val = eval('return '.$comm.'('.$key.');');
                }

                $fields[$pos]->setValue($val);
            }
        }
        else {
            $fields[$str]->setValue($key);
        }
    }

    public static function getFilledNum($val, $len){
        $_count = $len - strlen($val);
        $res = $val;

        // fill leading 0
        for ($i=0; $i<$_count; $i++){
            $res = '0'.$res;
        }

        return $res;
    }

    public static function getInstID($arg){
        return '0'.$arg;
    }

    // expect xxx.cc, and convert xxxcc
    public static function getMoney($arg){
        $moneyParts = split('\.',$arg);

        if (count($moneyParts) == 1){
            $moneyParts[1] = '00';
        }

        $inte = $moneyParts[0];
        $fra = '';
        if (strlen($moneyParts[1]) < 2){
            if (strlen($moneyParts[1]) == 0){
                $fra = $moneyParts[1].'00';
            }
            else if (strlen($moneyParts[1]) == 1){
                $fra = $moneyParts[1].'0';
            }
        }
        else if (strlen($moneyParts[1]) > 2){
            die('getMoney has format error: '.$moneyParts[1]);
        }
        else {
            $fra = $moneyParts[1];
        }

        return $inte.$fra;
    }
	
	public static function getLimitedName($arg){
		$nameLen = 30;
		$_name = '';
		
		if (strlen($arg) > $nameLen){
			$_name = substr($arg,0,$nameLen);
		}
		else {
			$_name = $arg;
		}
		
		return $_name;
	}
}

//$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('could not connect');
//mysql_select_db(DB_NAME);
//$sel = 'select *,substring(Costs,2) as Num_Costs,date_format(curdate(),\'%m/%d/%Y\') as Today from applications a join profiles p on a.ProfileID = p.ProfileID where AccountID > 3847 and AccountID < 3850';
//$sel1 = "SELECT * , substring( Costs, 2 ) AS Num_Costs,DATE_FORMAT(CURDATE(),'%m/%d/%Y') as TODAY,M.MONEYAMOUNT FROM MULTIPAYMENTS M, Applications A, Profiles P WHERE M.ACCOUNTID = A.AccountID 
//		AND A.ProfileID = P.ProfileID AND M.STATUS='0' AND M.FTPDATE='02/01/2014'";
//$sel2 = "select *,substring(Costs,2) as Num_Costs,DATE_FORMAT(CURDATE(),'%m/%d/%Y') as TODAY from Applications a join Profiles p on a.ProfileID = p.ProfileID 
//		where a.AccountID IN (SELECT DISTINCT ACCOUNTID FROM MULTIPAYMENTS WHERE STATUS='0' AND FTPDATE='02/01/2014')";
//$res1 = mysql_query($sel1);
//$res2 = mysql_query($sel2);

//if (MODE == 'TEST'){
//	file_put_contents('pad.txt','$$AAPASTD0152[TEST[NL$$'.PHP_EOL.utilities::db2PAD($res1));
//	file_put_contents('pds.txt','$$AAPDSTD0152[TEST[NL$$'.PHP_EOL.utilities::db2PDS($res2));
//}
//else {
//	file_put_contents('pad.txt','$$AAPASTD0152[PROD[NL$$'.PHP_EOL.utilities::db2PAD($res1));
//	file_put_contents('pds.txt','$$AAPDSTD0152[PROD[NL$$'.PHP_EOL.utilities::db2PDS($res2));
//}
//echo utilities::getJDFrom('05/06/2014');
//echo utilities::getJD();
//echo utilities::getLimitedName('abcd');
?>